package com.wqiuqiu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.wqiuqiu.common.R;
import com.wqiuqiu.common.to.es.HasWareTo;
import com.wqiuqiu.common.to.login.MemberResponseTo;
import com.wqiuqiu.common.to.mq.SecdKillOrderTo;
import com.wqiuqiu.gulimall.order.constant.OrderConstant;
import com.wqiuqiu.gulimall.order.entity.OrderItemEntity;
import com.wqiuqiu.gulimall.order.entity.PaymentInfoEntity;
import com.wqiuqiu.gulimall.order.enume.OrderStatusEnum;
import com.wqiuqiu.gulimall.order.feign.CartFeignService;
import com.wqiuqiu.gulimall.order.feign.MemberFeignService;
import com.wqiuqiu.gulimall.order.feign.ProductFeignService;
import com.wqiuqiu.gulimall.order.feign.WareFeignService;
import com.wqiuqiu.gulimall.order.interceptor.OrderInterceptor;
import com.wqiuqiu.gulimall.order.service.OrderItemService;
import com.wqiuqiu.gulimall.order.service.PaymentInfoService;
import com.wqiuqiu.gulimall.order.to.OrderCreateTo;
import com.wqiuqiu.gulimall.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqiuqiu.common.PageUtils;
import com.wqiuqiu.common.Query;

import com.wqiuqiu.gulimall.order.dao.OrderDao;
import com.wqiuqiu.gulimall.order.entity.OrderEntity;
import com.wqiuqiu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo toTrade() throws ExecutionException, InterruptedException {

        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberResponseTo memberResponseTo = OrderInterceptor.threadLocal.get();
        if (memberResponseTo != null) {

            //由于异步编排使用多线程，当前线程的上下文信息无法通过threadLocal来共享
            // 通过RequestContextHolder.setRequestAttributes(requestAttributes)来实现上下文信息共享
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

            //找到收获地址
            Long memberId = memberResponseTo.getId();
            CompletableFuture<Void> addressFutrue = CompletableFuture.runAsync(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                R r = memberFeignService.infoByMemberId(memberId);
                if (r.getCode() == 0) {
                    List<MemberAddressVo> data = r.getData(new TypeReference<List<MemberAddressVo>>() {
                    });
                    orderConfirmVo.setAddress(data);
                }
            }, executor);

            CompletableFuture<Void> cartFutrue = CompletableFuture.runAsync(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                R memberCart = cartFeignService.getMemberCart();
                if (memberCart.getCode() == 0) {
                    List<CartItemVo> data = memberCart.getData(new TypeReference<List<CartItemVo>>() {
                    });
                    BigDecimal totalPrice = new BigDecimal("0");
                    //只留下选中的购物项
                    List<CartItemVo> checkedItems = data.stream().filter(CartItemVo::isChecked).collect(Collectors.toList());

                    orderConfirmVo.setCartItems(checkedItems);
                    //计算总价和商品总件数
                    int totalNum = 0;
                    for (CartItemVo cartItemVo : checkedItems) {
                        totalPrice = totalPrice.add(cartItemVo.getPrice().multiply(new BigDecimal(cartItemVo.getCount())));
                        totalNum += cartItemVo.getCount();
                    }
                    orderConfirmVo.setTotalPrice(totalPrice);
                    orderConfirmVo.setTotalNum(totalNum);
                }
            }, executor).thenRunAsync(() -> {
                //查询是否有货
                List<Long> skuIds = orderConfirmVo.getCartItems().stream().map(CartItemVo::getSkuId).collect(Collectors.toList());
                R warebySkuIds = wareFeignService.getWarebySkuIds(skuIds);
                if (warebySkuIds.getCode() == 0) {
                    List<HasWareTo> data = warebySkuIds.getData(new TypeReference<List<HasWareTo>>() {
                    });
                    Map<Long, Long> map = data.stream().collect(Collectors.toMap(HasWareTo::getSkuId, HasWareTo::getStock));
                    List<CartItemVo> collect = orderConfirmVo.getCartItems().stream().peek((obj) -> {
                        if (map.get(obj.getSkuId()) > 0) {
                            obj.setHasStock(true);
                        } else {
                            obj.setHasStock(false);
                        }
                    }).collect(Collectors.toList());
                    orderConfirmVo.setCartItems(collect);
                }
            }, executor);
            //TODO 这里简单模拟，并没有真正实现，默认使用第一个地址的手机号码的最后一个数字为运费
            List<MemberAddressVo> address = orderConfirmVo.getAddress();
            if (address != null && address.size() > 0) {
                String mobile = address.get(0).getPhone();
                if (StringUtils.isNotEmpty(mobile)) {
                    orderConfirmVo.setFreight(new BigDecimal(mobile.substring(mobile.length() - 1)));
                }
            }
            CompletableFuture<Void> memberFutrue = CompletableFuture.runAsync(() -> {
                //查会员积分
                R info = memberFeignService.info(memberId);
                if (info.getCode() == 0) {
                    MemberResponseTo data = info.getData(new TypeReference<MemberResponseTo>() {
                    });
                    orderConfirmVo.setIntegration(data.getIntegration());
                }
            }, executor);

            CompletableFuture.allOf(addressFutrue, cartFutrue, memberFutrue).get();

            BigDecimal payPrice = orderConfirmVo.getTotalPrice();
            if (orderConfirmVo.getFreight() != null) {
                payPrice = payPrice.add(orderConfirmVo.getFreight());
            } else {
                orderConfirmVo.setFreight(new BigDecimal("0"));
            }
            if (orderConfirmVo.getIntegration() != null) {
                payPrice = payPrice.subtract(new BigDecimal(orderConfirmVo.getIntegration()));
            } else {
                orderConfirmVo.setIntegration(0);
            }
            orderConfirmVo.setPayPrice(payPrice);
            //放重令牌
            String uuid = UUID.randomUUID().toString();
            //redis存一份，页面存一份
            orderConfirmVo.setOrderToken(uuid);
            stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseTo.getId(), uuid);
        }
        return orderConfirmVo;
    }

    /**
     * 不适用setea，使用消息队列
     *
     * @param submit
     * @return
     */
//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitResponseVo submitOrder(OrderSubmitVo submit) {
        SubmitResponseVo responseVo = new SubmitResponseVo();
        responseVo.setCode(0);
        responseVo.setDate(new Date());
        //验令牌，防止重复提交订单
        String orderToken = submit.getOrderToken();
        if (StringUtils.isNotEmpty(orderToken)) {
            //保证原子性
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            MemberResponseTo memberResponseTo = OrderInterceptor.threadLocal.get();
            String key = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseTo.getId();
            Long execute = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(key), orderToken);
            if (execute == 1L) {
                //令牌验证成功，创建订单
                OrderCreateTo order = createOrder(submit);
                responseVo.setOrder(order.getOrder());
                //验价 都要自己重新查一遍？？？
                if (Math.abs(submit.getPayPrice().subtract(order.getOrder().getPayAmount()).doubleValue()) < 0.02) {
                    //验价成功
                    //锁库存
                    List<OrderLockVo> orderLockVos = order.getOrderItems().stream().map((obj) -> {
                        OrderLockVo orderLockVo = new OrderLockVo();
                        orderLockVo.setSkuId(obj.getSkuId());
                        orderLockVo.setCount(obj.getSkuQuantity());
                        return orderLockVo;
                    }).collect(Collectors.toList());
                    WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                    wareSkuLockVo.setLocks(orderLockVos);
                    wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                    R r = wareFeignService.orderLock(wareSkuLockVo);
                    if (r.getCode() == 0) {
                        //锁库存成功，保存订单，给延时队列发生订单创建消息
                        System.out.println(1/0);
                        saveOrder(order);
                        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder().getOrderSn());
                        log.info("成功创建订单...");
                        return responseVo;
                    } else {
                        String msg = (String) r.get("msg");
                        System.out.println(msg + "号商品库存不足");
                        responseVo.setCode(3);
                        return responseVo;
                    }

                } else {
                    responseVo.setCode(2);
                    return responseVo;
                }
            } else {
                responseVo.setCode(1);
                return responseVo;
            }
        } else {
            responseVo.setCode(1);
            return responseVo;
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity ordersn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        payVo.setTotal_amount(ordersn.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
        payVo.setBody(ordersn.getNote());
        payVo.setOut_trade_no(orderSn);
        //订单的主题 设置为该订单中的一个spuName
        List<OrderItemEntity> entitys = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setSubject(entitys.get(0).getSpuName());
        return payVo;
    }


    @Override
    public PageUtils queryPageMemberOrder(int pageNum) {

        //TODO　分页查询还有点问题，在做一下排序，最新的订单显示在最前面

        List<OrderVo> orderVos = new ArrayList<>();

        //先获取用户信息
        MemberResponseTo memberResponseTo = OrderInterceptor.threadLocal.get();

        //查询用户订单信息
        List<OrderEntity> orderEntities = this.list(new QueryWrapper<OrderEntity>().eq("member_id", memberResponseTo.getId()));
        //查出每一个订单项
        for (OrderEntity orderEntity : orderEntities) {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderEntity.getOrderSn()));
            OrderVo orderVo = new OrderVo();
            OrderVo.Order order = new OrderVo.Order();
            List<OrderVo.OrderItem> orderItems = new ArrayList<>();
            BeanUtils.copyProperties(orderEntity, order);
            orderVo.setOrder(order);
            for (OrderItemEntity orderItemEntity : orderItemEntities) {
                OrderVo.OrderItem orderItem = new OrderVo.OrderItem();
                BeanUtils.copyProperties(orderItemEntity, orderItem);
                orderItems.add(orderItem);
            }
            orderVo.setOrderItems(orderItems);
            orderVos.add(orderVo);
        }
        return new PageUtils(orderVos, orderVos.size(), 10, pageNum);
    }

    @Override
    public String handlerPayed(PayAsyncVo vo) {

        //保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            //付款成功，改变订单状态
            String tradeNo = vo.getOut_trade_no();
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setStatus(OrderStatusEnum.PAYED.getCode());
            baseMapper.update(orderEntity, new QueryWrapper<OrderEntity>().eq("order_sn", tradeNo));
            return "success";
        }
        return "failed";
    }

    @Override
    public void createSeckillOrder(SecdKillOrderTo to) {
        //创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(to.getOrderSn());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setMemberId(to.getMemberId());
        orderEntity.setPayAmount(to.getSeckillPrice().multiply(new BigDecimal(to.getNum())));
//        orderEntity.setMemberUsername(OrderInterceptor.threadLocal.get().getUsername());
        orderEntity.setCreateTime(new Date());
        //创建订单项
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(to.getOrderSn());
        orderItemEntity.setRealAmount(orderEntity.getPayAmount());
        orderItemEntity.setSkuId(to.getSkuId());
        CompletableFuture<Void> skuFutrue = CompletableFuture.runAsync(() -> {
            R r = productFeignService.info(to.getSkuId());
            if (r.getCode() == 0) {
                SkuInfoVo data = r.getData(new TypeReference<SkuInfoVo>() {
                });
                orderItemEntity.setSkuPic(data.getSkuDefaultImg());
                orderItemEntity.setSkuPrice(data.getPrice());
                orderItemEntity.setSkuName(data.getSkuName());
                orderItemEntity.setSkuQuantity(to.getNum());
            }
        }, executor);

        CompletableFuture<Void> spuFutrue = CompletableFuture.runAsync(() -> {
            R spu = productFeignService.getSpuinfoBySkuId(to.getSkuId());
            if (spu.getCode() == 0) {
                SpuInfoVo data = spu.getData(new TypeReference<SpuInfoVo>() {
                });
                orderItemEntity.setCategoryId(data.getCatalogId());
                orderItemEntity.setSpuName(data.getSpuName());
                orderItemEntity.setSpuBrand(String.valueOf(data.getBrandId()));
                orderItemEntity.setSpuId(data.getId());
            }
        }, executor);
        try {
            CompletableFuture.allOf(skuFutrue,spuFutrue).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        this.save(orderEntity);
        orderItemService.save(orderItemEntity);
    }

    @Override
    public void releaseOrder(String orderSn) {
        //释放库存
        try {
            R r = wareFeignService.unlockOrder(orderSn);
            if (r.getCode() == 0){
                //如果修改不成功，应该重试
                //修改订单状态
                OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
                orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
                orderEntity.setDeleteStatus(1);
                this.updateById(orderEntity);
            }
        }catch (Exception e){
            log.error("释放订单网络延时，正在重试...");
            //或者重新发给release消息队列
            releaseOrder(orderSn);
        }


    }

    private OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    private void saveOrder(OrderCreateTo order) {
        this.save(order.getOrder());
        orderItemService.saveBatch(order.getOrderItems());
    }

    private OrderCreateTo createOrder(OrderSubmitVo submit) {
        OrderCreateTo orderCreateTo = new OrderCreateTo();

        //订单号 数据库的设计长度是32
        String timeId = IdWorker.getTimeId().substring(0, 31);

        //全部订单项
        List<OrderItemEntity> orderItemEntities = createOrderItems(timeId);

        //生成订单实体
        OrderEntity orderEntity = createOrderEntity(submit, timeId, orderItemEntities);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);

        return orderCreateTo;
    }

    private OrderEntity createOrderEntity(OrderSubmitVo submit, String timeId, List<OrderItemEntity> orderItemEntities) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(timeId);
        //收货人信息
        Long addrId = submit.getAddrId();
        R info = memberFeignService.receiveaddressInfo(addrId);
        if (info.getCode() == 0) {
            MemberAddressVo data = info.getData(new TypeReference<MemberAddressVo>() {
            });

            orderEntity.setMemberId(data.getMemberId());
            orderEntity.setReceiverName(data.getName());
            orderEntity.setReceiverCity(data.getCity());
            orderEntity.setReceiverDetailAddress(data.getDetailAddress());
            orderEntity.setReceiverPhone(data.getPhone());
            orderEntity.setReceiverPostCode(data.getPostCode());
            orderEntity.setReceiverProvince(data.getProvince());
            orderEntity.setReceiverRegion(data.getRegion());
            orderEntity.setCreateTime(new Date());
            orderEntity.setMemberUsername(data.getName());
            R fare = memberFeignService.fare(data.getId());
            if (fare.getCode() == 0) {
                FareAddressVo fareAddressVo = fare.getData(new TypeReference<FareAddressVo>() {
                });
                orderEntity.setFreightAmount(fareAddressVo.getFare());
            }
        }

        //商品实际总价
        BigDecimal totolPrice = new BigDecimal("0");
        BigDecimal promotion_amount = new BigDecimal("0");
        BigDecimal integration_amount = new BigDecimal("0");
        BigDecimal coupon_amount = new BigDecimal("0");
        int integration = 0;
        int growth = 0;

        //应付金额，那些优惠已经在生成每一个订单项的时候，计算在实际金额里面了
        BigDecimal payPrice = new BigDecimal("0");

        for (OrderItemEntity entity : orderItemEntities) {
            integration = integration + entity.getGiftIntegration() * entity.getSkuQuantity();
            growth = growth + entity.getGiftGrowth() * entity.getSkuQuantity();
            coupon_amount = coupon_amount.add(entity.getCouponAmount());
            integration_amount = integration_amount.add(entity.getIntegrationAmount());
            promotion_amount = promotion_amount.add(entity.getPromotionAmount());
            totolPrice = totolPrice.add(entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity().toString())));
            //每一个购物项的实际金额*数量
            payPrice = payPrice.add(entity.getRealAmount().multiply(new BigDecimal(entity.getSkuQuantity().toString())));
        }
        payPrice = payPrice.subtract(orderEntity.getFreightAmount());
        orderEntity.setTotalAmount(totolPrice);
        orderEntity.setDiscountAmount(new BigDecimal("1")); //默认折扣1 不打折
        orderEntity.setPayType(1);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setPayAmount(payPrice);
        orderEntity.setIntegration(integration);
        orderEntity.setGrowth(growth);
        return orderEntity;
    }

    private List<OrderItemEntity> createOrderItems(String orderSn) {

        //根据用户购物车信息来决定有多少个订单项
        MemberResponseTo memberResponseTo = OrderInterceptor.threadLocal.get();
        R memberCart = cartFeignService.getMemberCart();
        List<OrderItemEntity> items = new ArrayList<>();
        if (memberCart.getCode() == 0) {
            //用户的购物车数据
            List<CartItemVo> data = memberCart.getData(new TypeReference<List<CartItemVo>>() {
            });
            //构建订单项
            for (CartItemVo itemVo : data) {
                OrderItemEntity orderItemEntity = createOrderItem(itemVo, orderSn);
                items.add(orderItemEntity);
            }

        }
        return items;
    }

    private OrderItemEntity createOrderItem(CartItemVo itemVo, String orderSn) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setSkuId(itemVo.getSkuId());
        orderItemEntity.setSkuAttrsVals(StringUtils.join(itemVo.getAttrs(), ','));
        orderItemEntity.setSkuName(itemVo.getSkuName());
        orderItemEntity.setSkuPic(itemVo.getSkuImage());
        orderItemEntity.setSkuPrice(itemVo.getPrice());
        orderItemEntity.setSkuQuantity(itemVo.getCount());
        //查询spu信息
        R spuinfoBySkuId = productFeignService.getSpuinfoBySkuId(itemVo.getSkuId());
        if (spuinfoBySkuId.getCode() == 0) {
            SpuInfoVo data = spuinfoBySkuId.getData(new TypeReference<SpuInfoVo>() {
            });
            //TODO 这里是brandId代替brandName
            orderItemEntity.setSpuBrand(data.getBrandId().toString());
            orderItemEntity.setSpuName(data.getSpuName());
            orderItemEntity.setSpuId(data.getId());
            //TODO 图片也需要查
//            orderItemEntity.setSpuPic(data.getSpuDescription());
        }
        orderItemEntity.setOrderSn(orderSn);

        //优惠信息
        orderItemEntity.setCouponAmount(new BigDecimal("0"));//优惠券优惠分解金额
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));//商品促销分解金额
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));//积分优惠分解金额
        orderItemEntity.setRealAmount(orderItemEntity.getSkuPrice().subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount().subtract(orderItemEntity.getPromotionAmount())));

        //积分信息，购买商品赠送积分,赠送成长值,根据商品的价格来决定
        orderItemEntity.setGiftGrowth(orderItemEntity.getSkuPrice().intValue());
        orderItemEntity.setGiftIntegration(orderItemEntity.getSkuPrice().intValue());
        return orderItemEntity;
    }

}